package com.atguigu.spzx.common.config.manager;

import jakarta.annotation.Resource;
import org.springframework.cache.CacheManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author LT
 * @create 2023-11-01-18:26
 */
@Configuration
public class SpzxRedisConfig implements InitializingBean {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

    }

       //LettuceConnectionFactory: redis的连接工厂，如果引入了redis的连接池，启动时，启动器会自动初始化连接工厂
    //配置缓存管理器到容器中
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory connectionFactory){
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600L)) //缓存过期时间
//                .disableCachingNullValues() //禁止缓存空值，默认缓存
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))//键的序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return RedisCacheManager
                .builder(connectionFactory) //使用连接工厂对象初始化builder对象
                .cacheDefaults(configuration) //给缓存管理器添加缓存策略配置
                .build();//创建cacheManager对象
    }

}
